package com.speedcar.base.advice;

import com.alibaba.fastjson.JSON;
import com.speedcar.base.model.ScResultJson;
import com.speedcar.base.result.ScResultWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.Collections;
import java.util.List;

/**
 * 对返回结果统一进行处理，包括返回结果格式统一包装
 *
 * @author zhangfuzeng
 */
@Slf4j
@RestControllerAdvice(basePackages = {"com.speedcar", "com.oldcar", "com.cyl"})
public class ScResponseAdvice implements ResponseBodyAdvice<Object> {


    @Autowired(required = false)
    private List<ScResultWrapper> resultWrappers = Collections.emptyList();

    @Autowired
    private ScResultWrapper scDefaultResultWrapper;

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    /**
     * 返回结果包装统一返回格式
     *
     * @return 包装后的返回结果
     */
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request,
                                  ServerHttpResponse response) {
        // 指定返回的结果为application/json格式，不指定，String类型转json后返回Content-Type是text/plain;charset=UTF-8
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);

        // 如果已经是包装类型，直接返回
        if (body instanceof ScResultJson) {
            return body;
        }

        // 检查是否为异常处理器的返回结果
        if (isExceptionHandlerReturn(returnType)) {
            return body; // 异常处理器返回的结果不进行二次包装
        }

        // 查找合适的包装器
        for (ScResultWrapper wrapper : resultWrappers) {
            if (wrapper != scDefaultResultWrapper && wrapper.supports(body)) {
                return wrapper.wrap(body);
            }
        }


        // 特殊处理String类型
        if (body instanceof String) {
            Object wrapped = scDefaultResultWrapper.wrap(body);
            return JSON.toJSONString(wrapped);
        }

        // 使用默认包装器
        if (scDefaultResultWrapper.supports(body)) {
            return scDefaultResultWrapper.wrap(body);
        }
        return body;
    }

    /**
     * 判断是否为异常处理器的返回
     */
    private boolean isExceptionHandlerReturn(MethodParameter returnType) {
        // 检查方法上是否有@ExceptionHandler注解
        return returnType.hasMethodAnnotation(ExceptionHandler.class);
    }
}
